package com.warmlight.voicepacket;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;

import com.warmlight.voicepacket.data.eventbus.AudioCompleted;
import com.warmlight.voicepacket.data.eventbus.PlayerServiceData;
import com.warmlight.voicepacket.utils.SPUtils;
import com.warmlight.voicepacket.widget.AudioPCMPlayer;
import com.warmlight.voicepacket.widget.AudioPlayer;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

/**
 * Created by jason on 2018/5/24.
 */

public class AudioService extends Service {

    private static final String TAG = "AudioService";
    private AudioPlayer mPlayer;
    private int[] countDownList = {R.raw.one,R.raw.two,R.raw.three,R.raw.four,R.raw.five,R.raw.six,R.raw.seven,R.raw.eight,R.raw.nine,R.raw.ten};
    private int countDown = 2;
    private PlayerServiceData mData;
    private AudioPCMPlayer soundTouchRec;
    private boolean isPCM;//是否是pcm
    private String playPath = "";
    private boolean isPause = false;

    @Override
    public void onCreate() {
        super.onCreate();
//        Log.e("Service","创建service");
        mPlayer = AudioPlayer.getInstance();
        EventBus.getDefault().register(this);

        mPlayer.setOnAudioCompletedListener(new AudioPlayer.AudioCompletedListener() {
            @Override
            public void AudioCompleted() {
                EventBus.getDefault().post(new AudioCompleted("completed"));
            }
        });
        soundTouchRec = AudioPCMPlayer.getInstance();
        soundTouchRec.setOnAudioCompletedListener(new AudioPCMPlayer.AudioCompletedListener() {
            @Override
            public void AudioCompleted() {
                EventBus.getDefault().post(new AudioCompleted("completed"));
            }
        });
    }

    //订阅方法，当接收到事件的时候，会调用该方法
    @Subscribe //(sticky = true)
    public void onEvent(PlayerServiceData data){
        if(data == null){
            Log.i(TAG,"PlayerServiceData == null");
            return;
        }else{
            mData = data;
        }

        String audioPath = data.getAudioPath();
        //测试用地址
//        audioPath = "http://nuanguang-img.oss-cn-shanghai.aliyuncs.com/yuyinbao%2F%E8%83%A1%E5%B0%8F%E5%85%AD%2F%E6%96%B0%E5%BD%95%E9%9F%B3%20113.mp3";
//        audioPath = "http://nuanguang-img.oss-cn-shanghai.aliyuncs.com/yuyinbao%2F20180803%2Fyuyinbao_20180803_76_6bbd0005b98490234040";
//        data.setAudioPath(audioPath);
        isPCM = false;
        if (audioPath.contains(".pcm")){
            isPCM = true;
        }
//        //添加延时判断
        if(!TextUtils.isEmpty(data.getDelay()) && mHandler!=null){
            //存在延时
            mHandler.removeMessages(0);
            mHandler.removeMessages(1);

            if (data.getAudioPath().equals(playPath)){
//                playPath = "";
                try {
                    if(mp!=null&&mp.isPlaying()){
                        mp.stop();
                        mp.release();
                        return;
                    }
                }catch (Exception e){
                    e.printStackTrace();
                }

                if (!isPCM) {
                    if (mPlayer.isPlayer()) {
                        mPlayer.pause();
                        isPause = true;
                        return;
                    }else{
                        if (isPause) {
                            mPlayer.play(data.getAudioPath());
                            isPause = false;
                            return;
                        }
                    }
                }else{
                    if (soundTouchRec.isPlaying()){
                        stopPCM();
                        return;
                    }else{
                        playPCM(data.getAudioPath());
                        return;
                    }
                }


            }else{
                mPlayer.stop();
                stopPCM();
                isPause = false;
            }
            playPath = data.getAudioPath();



            if (data.isFloat()){
                countDown = (int) (SPUtils.getFloatVoiceDelayTime() / 1000);
            }else {
                countDown = (int) (SPUtils.getVoiceDelayTime() / 1000);
            }

            mHandler.sendEmptyMessage(0);
            return;
        }

        switch (data.getCode()){
            case PlayerServiceData.PLAY:
//                Log.e(TAG,"播放！");
                if(mPlayer == null){
                    mPlayer = AudioPlayer.getInstance();
                }

                if (soundTouchRec == null){
                    soundTouchRec = AudioPCMPlayer.getInstance();
                }
//                if(mPlayer.getStatus() == AudioPlayer.Status.PLAYING.ordinal()){
//                    mPlayer.stop();
//                }
                if (isPCM){
                    mPlayer.stop();
                    playPCM(data.getAudioPath());
                }else {
                    stopPCM();
                    mPlayer.play(data.getAudioPath());
                }
                break;
            case PlayerServiceData.PAUSE:
                if(mPlayer != null){
                    mPlayer.pause();
                }
                stopPCM();
                break;
            case PlayerServiceData.STOP:
                if(mPlayer != null){
                    mPlayer.stop();
                }
                stopPCM();
                break;
            case PlayerServiceData.RESUME:
                //从封装保护的角度来说，unused,not reach.
                if (isPCM){
                    playPCM(data.getAudioPath());
                }else {
                    if (mPlayer != null) {
                        mPlayer.resume();
                    }
                }
                break;
            default:
                break;
        }
    }
    private void playPCM(String path){
        if (soundTouchRec == null) {
            soundTouchRec = AudioPCMPlayer.getInstance();
        }

        soundTouchRec.startPlay(path);
    }

    private void stopPCM(){
        if (soundTouchRec != null) {
            soundTouchRec.stopPlay(false);
        }
    }

    private MediaPlayer mp;
    private Handler mHandler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what){
                case 0:
                    if(countDown==0){
                        if(mPlayer == null){
                            mPlayer = AudioPlayer.getInstance();
                        }
                        if(soundTouchRec == null){
                            soundTouchRec = AudioPCMPlayer.getInstance();
                        }
                        if(mData!=null){
                            if (isPCM){
                                mPlayer.stop();
                                playPCM(mData.getAudioPath());
                            }else {
                                stopPCM();
                                mPlayer.play(mData.getAudioPath());
                            }
                        }
                        return;
                    }

                    mp = MediaPlayer.create(AudioService.this,countDownList[countDown-1]);
                    mp.start();

                    mHandler.sendEmptyMessageDelayed(1,1000 * countDown + 1000);
                    break;
                case 1:
                    if(mPlayer == null){
                        mPlayer = AudioPlayer.getInstance();
                    }
                    if(soundTouchRec == null){
                        soundTouchRec = AudioPCMPlayer.getInstance();
                    }
                    if(mData!=null){
                        if (isPCM){
                            mPlayer.stop();
                            playPCM(mData.getAudioPath());
                        }else {
                            stopPCM();
                            mPlayer.play(mData.getAudioPath());
                        }
                    }
                    if(mp != null){
                        mp.stop();
                        mp.release();
                        mp = null;
                    }
                    break;
            }

        }
    };

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
        if(mHandler!=null){
            mHandler.removeMessages(0);
            mHandler.removeMessages(1);
            mHandler = null;
        }
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}
